package com.masterclient.app.modules.income;

import android.content.Intent;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.baselibrary.utils.DoubleClickUtil;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.utils.StringsUtils;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.R;
import com.masterclient.app.base.FragmentHostActivity;
import com.masterclient.app.base.ProgressLoginDialog;
import com.masterclient.app.modules.income.dealer.DealerBankCardInsertActivity;
import com.masterclient.app.modules.income.dealer.model.DealerBankCardBean;
import com.masterclient.app.modules.income.contract.ApplyWithdrawContract;
import com.masterclient.app.modules.income.contract.ApplyWithdrawPresenter;
import com.masterclient.app.modules.income.model.ApplyWithdrawBean;
import com.masterclient.app.modules.income.model.WithdrawChargeBean;
import com.masterclient.app.modules.income.widget.ApplyWithdrawDialog;
import com.masterclient.app.modules.income.widget.SelectBankCardDialog;
import com.masterclient.app.utils.CaptchaUtil;

import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

import static com.masterclient.app.modules.income.WithdrawDetailsFragment.PAGE_TYPE;
import static com.masterclient.app.modules.income.WithdrawDetailsFragment.WITHDRAW_DETAILS;

@Route(path = AroutePath.APPLY_WITHDRAW_FRAGMENT)
public class ApplyWithdrawFragment extends BaseFragment<ApplyWithdrawPresenter> implements ApplyWithdrawContract.View {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_bank_name)
    TextView tvBankName;
    @BindView(R.id.tv_bank_code)
    TextView tvBankCode;
    @BindView(R.id.tv_balance)
    TextView tvBalance;
    @BindView(R.id.et_withdraw_money)
    EditText etWithdrawMoney;
    @BindView(R.id.tv_withdraw)
    TextView tvWithdraw;

    private ApplyWithdrawDialog applyWithdrawDialog;
    private ApplyWithdrawBean dataBean;
    private CaptchaUtil captchaUtil;
    private SPUtils spUtils;
    private CountDownTimer timer2;
    private String phoneNum;
    private String bankCardCertId;
    private SelectBankCardDialog selectBankCardDialog;
    private String totalAmount;

    public static ApplyWithdrawFragment newInstance() {
        return new ApplyWithdrawFragment();
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_apply_withdraw, null);
    }

    @Override
    protected void initOnlyOnce() {
        super.initOnlyOnce();

        spUtils = SPUtils.getInstance();
        tvWithdraw.setClickable(false);
        Utils.setDin(etWithdrawMoney, getActivity());
        showSoftInput(etWithdrawMoney);
        etWithdrawMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                double inputMoney = 0;
                double availableMoney = 0;
                double etMoney = 0;
                if (!TextUtils.isEmpty(s.toString()) && isNumeric(s.toString()) && !".".equals(s.toString())) {
                    inputMoney = Double.parseDouble(s.toString());
                }
                if (dataBean != null && !TextUtils.isEmpty(dataBean.availableBalance) &&
                        isNumeric(dataBean.availableBalance) && !".".equals(dataBean.availableBalance)) {
                    availableMoney = Double.parseDouble(dataBean.availableBalance);
                }
                if (inputMoney > availableMoney && dataBean != null) {
                    etWithdrawMoney.setText(dataBean.availableBalance);
                    etWithdrawMoney.setSelection(etWithdrawMoney.getText().toString().length());
                }

                if (!TextUtils.isEmpty(etWithdrawMoney.getText().toString()) && isNumeric(etWithdrawMoney.getText().toString()) &&
                        !".".equals(etWithdrawMoney.getText().toString())) {
                    etMoney = Double.parseDouble(etWithdrawMoney.getText().toString());
                }

                // 判断小数点后只能输入两位
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0, s.toString().indexOf(".") + 3);
                        etWithdrawMoney.setText(s);
                        etWithdrawMoney.setSelection(s.length());
                    }
                }

                if (etWithdrawMoney.getText().toString().length() > 0 && etMoney > 0) {
                    tvWithdraw.setClickable(true);
                    tvWithdraw.setBackgroundResource(R.drawable.shape_radius24_fc2a52);
                } else {
                    tvWithdraw.setClickable(false);
                    tvWithdraw.setBackgroundResource(R.drawable.shape_radius24_f0f2f5);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mPresenter.getWithdrawPreviewData();
    }

    public boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
        return pattern.matcher(str).matches();
    }

    @Override
    public void onResume() {
        super.onResume();

        captchaUtil = new CaptchaUtil(mContext, "验证码登录");
        captchaUtil.setCaptchaListerner(new CaptchaUtil.CaptchaListerner() {
            @Override
            public void onSuccess(String ne) {
                if (!TextUtils.isEmpty(phoneNum)) {
                    ProgressLoginDialog progressLoginDialog = new ProgressLoginDialog(getActivity());
                    mPresenter.getCaptcha(phoneNum, "withdraw", ne,progressLoginDialog);
                }
            }

            @Override
            public void onFailed() {

            }
        });
    }

    @OnClick({R.id.back, R.id.tv_withdraw_all, R.id.tv_withdraw, R.id.view_exchange_bank})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                Objects.requireNonNull(getActivity()).finish();
                break;
            case R.id.tv_withdraw_all:
                if (dataBean != null) {
                    etWithdrawMoney.setText(dataBean.availableBalance);
                    etWithdrawMoney.setSelection(etWithdrawMoney.getText().toString().length());
                }
                break;
            case R.id.tv_withdraw:
                if (!DoubleClickUtil.isClick(1000) || dataBean == null) {
                    return;
                }
                ProgressLoginDialog progressLoginDialog = new ProgressLoginDialog(getActivity());
                mPresenter.withdrawCharge(etWithdrawMoney.getText().toString().trim(),progressLoginDialog);
                break;
            case R.id.view_exchange_bank:
                ProgressLoginDialog progressLoginDialog2 = new ProgressLoginDialog(getActivity());
                mPresenter.getBankCardInfo(progressLoginDialog2);
                break;

        }
    }

    public static final int REFRESH_CARD = 3;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case REFRESH_CARD:
                if (data != null) {
                    if (selectBankCardDialog != null) {
                        selectBankCardDialog.dismiss();
                    }
                    this.bankCardCertId = data.getStringExtra("bankcardCertId");
                    if (selectBankCardDialog != null){
                        selectBankCardDialog.updateBankCardCertId(bankCardCertId);
                    }
                    tvBankName.setText(data.getStringExtra("bankName"));
                    String bankCode = data.getStringExtra("bankCode");
                    if (!TextUtils.isEmpty(bankCode) && bankCode.length() > 4) {
                        String firstStr = bankCode.substring(0, 4);
                        String endStr = bankCode.substring(bankCode.length() - 4);
                        tvBankCode.setText(String.format("%s **** **** **** %s", firstStr, endStr));
                    }
                }
                break;
        }
    }

    @Override
    public void showData(ApplyWithdrawBean dataBean) {
        if (dataBean != null) {
            this.dataBean = dataBean;
            this.bankCardCertId = dataBean.bankcardCertId;
            if (selectBankCardDialog != null){
                selectBankCardDialog.updateBankCardCertId(bankCardCertId);
            }
            tvBankName.setText(dataBean.bankShortName);
            tvBankCode.setText(dataBean.bankCard);

            String firstStr = "可用金额 ¥" + dataBean.availableBalance + "（最小提现金额";
            String lastStr = "可用金额 ¥" + dataBean.availableBalance + "（最小提现金额" + dataBean.minAmount;
            String AllStr = "可用金额 ¥" + dataBean.availableBalance + "（最小提现金额" + dataBean.minAmount + "元）";
            SpannableString spannableString = new SpannableString(AllStr);
            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#E79635")), 5, 6 + dataBean.availableBalance.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#E79635")), firstStr.length(), lastStr.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
            tvBalance.setText(spannableString);
        }
    }

    @Override
    public void applyWithdrawSuccess(ApplyWithdrawBean dataBean) {
        Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.WITHDRAW_DETAILS_FRAGMENT)
                .withString(PAGE_TYPE, WITHDRAW_DETAILS)
                .withString("withdraw_id", dataBean.bookId)
                .navigation();
        FragmentHostActivity.openFragment(getActivity(), fragment);
        getActivity().finish();
    }

    @Override
    public void showDataFailed(String msg) {
        ToastUtil.showToast(msg);
    }

    @Override
    public void getBankSuccess(List<DealerBankCardBean> data) {
        selectBankCardDialog = new SelectBankCardDialog(getActivity(), data,bankCardCertId);
        selectBankCardDialog.setOnButtonClickListener(new SelectBankCardDialog.OnBankCardClickListener() {
            @Override
            public void bankCardClickListener(String bankShortName, String bankCode, String bankcardCertId) {
                bankCardCertId = bankcardCertId;
                if (selectBankCardDialog != null){
                    selectBankCardDialog.updateBankCardCertId(bankCardCertId);
                }
                tvBankName.setText(bankShortName);
                tvBankCode.setText(bankCode);
                selectBankCardDialog.dismiss();
                ToastUtil.showToast("更换成功");
            }

            @Override
            public void addBankClickListener() {
                Intent intent = new Intent(getActivity(), DealerBankCardInsertActivity.class);
                intent.putExtra("from_type", "applyWithdrawPage");
                startActivityForResult(intent, 3);
            }
        });
        selectBankCardDialog.show();
    }

    @Override
    public void getBankCardFail(String msg) {
        ToastUtil.showToast(msg);
    }

    @Override
    public void withdrawChargeSuccess(WithdrawChargeBean data) {
        totalAmount = data.totalAmount;
        applyWithdrawDialog = new ApplyWithdrawDialog(getActivity(), data);
        applyWithdrawDialog.setOnGetCaptchaClickListener(new ApplyWithdrawDialog.OnGetCaptchaClickListener() {
            @Override
            public void getCaptchaClickListener(String phone) {
                if (StringsUtils.isPhoneNum(phone)) {
                    phoneNum = phone;
                    if (SystemConfigStorage.getInstance().isOpenSlipPageCode()) {
                        if (CaptchaUtil.CAPTCHA_NUMBER_TIMES >= Config.CAPTCHA_MAX_TIMES) {
                            ProgressLoginDialog progressLoginDialog = new ProgressLoginDialog(getActivity());
                            mPresenter.getCaptcha(phone, "withdraw", "",progressLoginDialog);
                        } else {
                            captchaUtil.start();
                        }
                    } else {
                        ProgressLoginDialog progressLoginDialog = new ProgressLoginDialog(getActivity());
                        mPresenter.getCaptcha(phone, "withdraw", "",progressLoginDialog);
                    }
                } else {
                    showToast("请输入正确的手机号");
                }
            }

            @Override
            public void submitClickListener(String phoneNum, String captcha) {
                ProgressLoginDialog progressLoginDialog = new ProgressLoginDialog(getActivity());
                mPresenter.applyWithdraw(bankCardCertId, totalAmount, phoneNum, captcha,progressLoginDialog);
            }
        });
        applyWithdrawDialog.show();
    }

    @Override
    public void withdrawChargeFail(String msg) {
        ToastUtil.showToast(msg);
    }

    @Override
    public void getCaptchaResult(String result) {
        if (Boolean.parseBoolean(result)) {//获取验证码成功
            spUtils.put(Config.APPLY_WITHDRAW_VERIFY_TIME, System.currentTimeMillis());
            applyWithdrawDialog.setViewCodePage();
        } else {
            showToast("获取验证码失败，请重试");
        }
    }

    @Override
    public void showError(String msg) {
        ToastUtil.showToast(msg);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if ((timer2 != null)) {
            timer2.cancel();
        }
    }
}
